<template>
  <div class="search">
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()">
    </van-nav-bar>

    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="search"
    >
      <template #action>
        <div @click="clickSearch">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-if="sugList.length > 0">
      <van-cell v-for="(item,index) in sugList" :key="item" icon="search">
        <div v-html="item" @click="clickSuggestion(index)"></div>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录">
      </van-cell>
      <van-cell v-for="(item,index) in hisList" :key="item"  :title="item" @click="searchHis(item,index)">
        <van-icon name="close" @click.stop="delHistory(index)"/>
      </van-cell>
    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { reqGetSug } from '@/api/search'
import { setHistory, getHistory } from '@/utlis/storage.js'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      hisList: getHistory(),
      oldList: []
    }
  },
  computed: {
    sugList () {
      // 拿到了输入框的内容,没有做任何 处理
      // 直接做 正则表达
      let searchText = this.keyword
      const specialCharacter = ['\\', '$', '(', ')', '*', '+', '.', '[', '?', '^', '{', '|']
      specialCharacter.map(v => {
        const reg = new RegExp('\\' + v, 'gim')
        searchText = searchText.replace(reg, '\\' + v)
      })
      const regExp = new RegExp(searchText, 'ig')
      return this.oldList.map(item =>
        item.replace(regExp, (match) => `<span style="color: red;">${match}</span>`)
      )
    }
  },
  methods: {
    search () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        // 检查当前关键字是否为空
        if (this.keyword === '') {
          this.oldList = []
          return
        }
        const res = await reqGetSug(this.keyword)
        this.oldList = res.data.options
      }, 300)
    },
    // 点击搜索按钮
    clickSearch () {
      if (this.keyword === '') return
      this.addHistory(this.keyword)
      this.$router.push({ name: 'SearchResult', query: { keyword: this.keyword } })
    },
    // 点击联想推荐
    clickSuggestion (index) {
      this.keyword = this.oldList[index]
      this.search(this.oldList[index])
      this.addHistory(this.oldList[index])
    },
    // 添加历史
    addHistory (str) {
      const index = this.hisList.findIndex(item => item === str)
      if (index !== -1) {
        // 说明历史记录中已经有了这一项, 应该删除掉
        this.hisList.splice(index, 1)
      }
      this.hisList.unshift(str)
      setHistory(this.hisList)
    },
    delHistory (index) {
      this.hisList.splice(index, 1)
      setHistory(this.hisList)
    },
    searchHis (item, index) {
      this.keyword = item
      this.search()
      this.hisList.splice(index, 1)
      this.hisList.unshift(item)
    }
  }
}
</script>

<style lang="" scoped>

</style>
